package net.chasing.androidbaseconfig.decoration;

import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class StickHeaderDecoration extends RecyclerView.ItemDecoration {
    public interface StickHeaderInterface {
        /**
         * is this item need stick
         *
         * @param position now item position in the recyclerView
         * @return true : need stick else not
         */
        boolean isStick(int position);

        void onClickHeader(RecyclerView.ViewHolder viewHolder, int position, float x, float y);
    }

    private final RecyclerView recyclerView;
    private final RecyclerView.LayoutManager manager;
    private final RecyclerView.Adapter adapter;
    private RecyclerView.ViewHolder viewHolder;
    private int mViewType;
    private final StickHeaderInterface stickHeaderInterface;

    private int headerPosition;
    private int headerHeight;
    private boolean isPressHeader;

    /**
     * 进行一些容错检查
     */
    public StickHeaderDecoration(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
        manager = recyclerView.getLayoutManager();
        adapter = recyclerView.getAdapter();
        if (adapter == null) {
            throw new RuntimeException("please set Decoration after set adapter");
        }

        if (adapter instanceof StickHeaderInterface) {
            stickHeaderInterface = (StickHeaderInterface) adapter;
            recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
                @Override
                public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                    if (e.getAction() == MotionEvent.ACTION_DOWN) {
                        float y = e.getY();
                        if (y <= headerHeight) {
                            isPressHeader = true;
                        }
                    } else if (e.getAction() == MotionEvent.ACTION_MOVE && isPressHeader) {
                        // 移动超出header范围，则视为无效点击
                        float y = e.getY();
                        if (y > headerHeight) {
                            isPressHeader = false;
                        }
                    } else if (e.getAction() == MotionEvent.ACTION_UP && isPressHeader) {
                        isPressHeader = false;
                        float y = e.getY();
                        if (y <= headerHeight) {
                            ((StickHeaderInterface) adapter).onClickHeader(viewHolder, headerPosition, e.getX(), y);
//                            rv.scrollToPosition(headerPosition);
                        }
                        return true;
                    }
                    return false;
                }

                @Override
                public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {

                }

                @Override
                public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

                }
            });
            return;
        }
        throw new RuntimeException("please make your adapter implements StickHeaderInterface");
    }

    /**
     * 绘制头部的stick view
     */
    @Override
    public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.onDrawOver(c, parent, state);
        View childAt = parent.getChildAt(0);
        if (childAt == null)
            return;

        int position;
        if (manager instanceof LinearLayoutManager) {
            position = ((LinearLayoutManager) manager).findFirstVisibleItemPosition();
        } else {
            RecyclerView.ViewHolder childViewHolder = parent.getChildViewHolder(childAt);
            position = childViewHolder.getLayoutPosition();
        }
        for (int i = position; i >= 0; i--) {
            if (stickHeaderInterface.isStick(i)) {
                headerPosition = i;
                int top = 0;
                if (position + 1 < adapter.getItemCount()) {
                    if (stickHeaderInterface.isStick(position + 1)) {
                        View childNext = parent.getChildAt(1);
                        if (childNext != null)
                            top = Math.max(manager.getDecoratedTop(childNext), 0);
                    }
                }
                int viewType = adapter.getItemViewType(i);
                if (viewHolder == null || viewType != mViewType) {
                    mViewType = viewType;
                    viewHolder = adapter.createViewHolder(parent, viewType);
                }
                adapter.bindViewHolder(viewHolder, i);
                int itemViewHeight = getMeasureHeight(viewHolder.itemView);
                c.save();
                if (top < viewHolder.itemView.getMeasuredHeight() && top > 0) {
                    c.translate(0, top - itemViewHeight);
                    headerHeight = top;
                } else {
                    headerHeight = itemViewHeight;
                }
                viewHolder.itemView.draw(c);
                c.restore();
                return;
            }
        }
    }

    /**
     * 测量控件的高度
     */
    private int getMeasureHeight(View header) {
        int widthSpec = View.MeasureSpec.makeMeasureSpec(recyclerView.getWidth(), View
                .MeasureSpec.EXACTLY);
        int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        header.measure(widthSpec, heightSpec);
        header.layout(0, 0, header.getMeasuredWidth(), header.getMeasuredHeight());
        return header.getMeasuredHeight();
    }
}
